package com.imooc.town.service.impl;

import com.fasterxml.jackson.databind.BeanProperty;
import com.imooc.town.converter.OrderMaster2OrderDTOConverter;
import com.imooc.town.dataobject.OrderDetail;
import com.imooc.town.dataobject.OrderMaster;
import com.imooc.town.dataobject.ProductInfo;
import com.imooc.town.dto.CartDTO;
import com.imooc.town.dto.OrderDTO;
import com.imooc.town.enums.OrderStatusEnum;
import com.imooc.town.enums.PayStatusEnum;
import com.imooc.town.enums.ResultEnum;
import com.imooc.town.exception.SellException;
import com.imooc.town.reponsitory.OrderDetailReponsitory;
import com.imooc.town.reponsitory.OrderMasterReponsitory;
import com.imooc.town.service.OrderService;
import com.imooc.town.service.PayService;
import com.imooc.town.service.ProductService;
import com.imooc.town.service.PushMessageService;
import com.imooc.town.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by 10077 on 2018/3/21.
 * desc:
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService productService;
    @Autowired
    private OrderMasterReponsitory orderMasterReponsitory;
    @Autowired
    private OrderDetailReponsitory orderDetailReponsitory;
    @Autowired
    private PushMessageService pushMessageService;
    @Autowired
    private PayService payService;


    @Override
    public OrderDTO createOrder(OrderDTO orderDTO) {
        BigDecimal orderAmount = new BigDecimal ( BigInteger.ZERO );
        String orderId = KeyUtil.getUniqueKey ();

//       1、 查询商品（数量，和价格）
        for (OrderDetail orderDetail: orderDTO.getOrderDetailList ()) {
            ProductInfo productInfo = productService.getOne ( orderDetail.getProductId () );
            if (productInfo==null){
                throw new SellException( ResultEnum.PRODUCT_NOT_EXIST);
            }
            // 2、计算商品的总价
            orderAmount = productInfo.getProductPrice ().multiply ( new BigDecimal (  orderDetail.getProductQuantity () )).add ( orderAmount );
//            详情入库
            orderDetail.setDetailId ( KeyUtil.getUniqueKey () );
            orderDetail.setOrderId ( orderId );
            BeanUtils.copyProperties ( productInfo,orderDetail );
            orderDetailReponsitory.save ( orderDetail );
        }

//        3、写入订单数据库（ordermaster和orderditail）
        OrderMaster orderMaster = new OrderMaster ();
        orderDTO.setOrderId ( orderId );
        BeanUtils.copyProperties ( orderDTO,orderMaster );
        orderMaster.setOrderAmount ( orderAmount );
        orderMaster.setOrderStatus ( OrderStatusEnum.NEW.getCode () );
        orderMaster.setPayStatus ( PayStatusEnum.WAIT.getCode () );
        orderMasterReponsitory.save ( orderMaster );

//      4、扣库存

        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList ().stream ().map(e->
                new CartDTO ( e.getProductId (),e.getProductQuantity () )).collect( Collectors.toList());
        productService.decreaseStock ( cartDTOList );

//       5、推送消息
        pushMessageService.orderStatus ( orderDTO );
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {

        OrderMaster orderMaster = orderMasterReponsitory.getOne ( orderId );
        if (orderMaster == null){
            throw  new SellException ( ResultEnum.ORDER_NOT_EXIST );
        }
        List<OrderDetail> orderDetailList = orderDetailReponsitory.findByOrderId ( orderId );
        OrderDTO orderDTO = new OrderDTO ();
        BeanUtils.copyProperties ( orderMaster,orderDTO );
        orderDTO.setOrderDetailList ( orderDetailList );

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findAllOrder(String openid, Pageable pageable) {

        Page<OrderMaster> orderMasterPage = orderMasterReponsitory.findByBuyerOpenid ( openid,pageable );
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert ( orderMasterPage.getContent () );
        return new PageImpl<OrderDTO> ( orderDTOList,pageable,orderMasterPage.getTotalElements () );
    }

    @Override
    @Transactional
    public OrderDTO cancle(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();

        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterReponsitory.save(orderMaster);
        if (updateResult == null) {
            log.error("【取消订单】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        //返回库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【取消订单】订单中无商品详情, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productService.increateStock (cartDTOList);

        //如果已支付, 需要退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            payService.refund(orderDTO);
        }
        return orderDTO;
    }




    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {

        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【完结订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterReponsitory.save(orderMaster);
        if (updateResult == null) {
            log.error("【完结订单】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

//        返回微信消息

        pushMessageService.orderStatus ( orderDTO );

        return orderDTO;
    }

    @Override
    public OrderDTO paid(OrderDTO orderDTO) {

        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【订单支付完成】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.error("【订单支付完成】订单支付状态不正确, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        //修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterReponsitory.save(orderMaster);
        if (updateResult == null) {
            log.error("【订单支付完成】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }



        return orderDTO;
    }

    @Override
    public Page<OrderDTO> list(Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterReponsitory.findAll(pageable);

        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        return new PageImpl<>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }
}
